function withData(param) {
  return param < 10 ? '0' + param : '' + param;
}

function getLoopArray(start, end) {
  const arr = [];
  for (let i = start; i <= end; i++) {
    arr.push(withData(i));
  }
  return arr;
}

function getMonthDay(year, month) {
  const flag = year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
  let day = 0;
  switch (month) {
    case '01':
    case '03':
    case '05':
    case '07':
    case '08':
    case '10':
    case '12':
      day = 31;
      break;
    case '04':
    case '06':
    case '09':
    case '11':
      day = 30;
      break;
    case '02':
      day = flag ? 29 : 28;
      break;
    default:
      day = 0;
      break;
  }
  return day;
}

function getDays(year, month) {
  const numYear = parseInt(year);
  const numMonth = parseInt(month);
  const day = getMonthDay(numYear, withData(numMonth));
  return getLoopArray(1, day);
}

function dateTimePicker(startYear, endYear, date) {
  const years = getLoopArray(startYear, endYear);
  const months = getLoopArray(1, 12);
  const hours = getLoopArray(0, 23);
  const minutes = getLoopArray(0, 59);

  const defaultDate = date ? new Date(date) : new Date();
  const defaultYear = defaultDate.getFullYear().toString();
  const defaultMonth = withData(defaultDate.getMonth() + 1);
  const defaultDay = withData(defaultDate.getDate());
  const defaultHour = withData(defaultDate.getHours());
  const defaultMinute = withData(defaultDate.getMinutes());

  const days = getDays(defaultYear, defaultMonth);

  const dateTimeArray = [years, months, days, hours, minutes];
  const dateTime = [
    years.indexOf(defaultYear),
    months.indexOf(defaultMonth),
    days.indexOf(defaultDay),
    hours.indexOf(defaultHour),
    minutes.indexOf(defaultMinute)
  ];

  return {
    dateTimeArray: dateTimeArray,
    dateTime: dateTime
  };
}

module.exports = {
  dateTimePicker: dateTimePicker,
  getDays: getDays
}; 